<template>
  <div class="user-profile">
    <NavBar />
    <main class="container">
      <h1>个人中心</h1>
      
      <LoadingSpinner v-if="isLoading" message="正在加载用户信息..." />
      
      <div v-else-if="error" class="error-message-box">
        <p>{{ error }}</p>
        <button @click="fetchUserProfile" class="retry-button">重试</button>
      </div>
      
      <div v-else class="profile-content">
        <!-- 个人资料卡片 -->
        <div class="profile-card">
          <div class="profile-header">
            <div class="avatar-container">
              <img class="avatar" :src="previewAvatar || avatarUrl || '/avatar.PNG'" alt="用户头像" @error="handleImageError">
              <div class="avatar-overlay">
                <input type="file" id="avatar-upload" accept="image/*" @change="handleAvatarChange" style="display: none">
                <button class="edit-avatar" @click="triggerFileUpload">
                  <i class="icon-camera"></i>
                  更换头像
                </button>
              </div>
            </div>
            
            <div class="user-info">
              <h2>{{ user.username }}</h2>
              <p class="user-status">{{ user.department }} · {{ user.student_id }}</p>
              <div class="user-balance-container">
                <p class="user-balance">余额: <span class="balance-amount">¥{{ user.balance || 0 }}</span></p>
                <button class="btn-recharge" @click="showRechargeModal = true">充值</button>
              </div>
              <div class="user-stats">
                <div class="stat-item clickable" @click="navigateToBooks('selling')">
                  <span class="stat-value">{{ user.publishedCount }}</span>
                  <span class="stat-label">已发布</span>
                </div>
                <div class="stat-item clickable" @click="navigateToBooks('sold')">
                  <span class="stat-value">{{ user.soldCount }}</span>
                  <span class="stat-label">已售出</span>
                </div>
                <div class="stat-item clickable" @click="navigateToBooks('purchased')">
                  <span class="stat-value">{{ user.boughtCount }}</span>
                  <span class="stat-label">已购买</span>
                </div>
                <div class="stat-item clickable" @click="navigateToBooks('favorite')">
                  <span class="stat-value">{{ user.favoriteCount }}</span>
                  <span class="stat-label">收藏</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="tab-container">
          <div class="tab-buttons">
            <button 
              class="tab-btn" 
              :class="{ active: activeTab === 'account' }" 
              @click="activeTab = 'account'"
            >
              账号信息
            </button>
            <button 
              class="tab-btn" 
              :class="{ active: activeTab === 'security' }" 
              @click="activeTab = 'security'"
            >
              安全设置
            </button>
            <button 
              class="tab-btn" 
              :class="{ active: activeTab === 'notification' }" 
              @click="activeTab = 'notification'"
            >
              消息通知
            </button>
          </div>
          
          <div class="tab-content">
            <!-- 账号信息面板 -->
            <div v-if="activeTab === 'account'" class="account-panel">
              <form @submit.prevent="updateAccount">
                <div class="form-group">
                  <label for="username">用户名</label>
                  <input type="text" id="username" v-model="accountForm.username" disabled readonly>
                  <small>用户名不可修改</small>
                </div>
                
                <div class="form-group">
                  <label for="real-name">真实姓名</label>
                  <input type="text" id="real-name" v-model="accountForm.real_name" required>
                </div>
                
                <div class="form-group">
                  <label for="department">所在学院</label>
                  <input type="text" id="department" v-model="accountForm.department" required>
                </div>
                
                <div class="form-group">
                  <label for="student-id">学号</label>
                  <input type="text" id="student-id" v-model="accountForm.student_id" required>
                </div>
                
                <div class="form-group">
                  <label for="email">邮箱</label>
                  <input type="email" id="email" v-model="accountForm.email" required>
                </div>
                
                <div class="form-group">
                  <label for="phone">手机号</label>
                  <input type="tel" id="phone" v-model="accountForm.phone" pattern="[0-9]{11}">
                </div>
                
                <div class="form-group">
                  <label for="wechat">微信号</label>
                  <input type="text" id="wechat" v-model="accountForm.wechat">
                </div>
                
                <div class="form-group">
                  <label for="bio">个人简介</label>
                  <textarea id="bio" v-model="accountForm.bio" rows="4"></textarea>
                </div>
                
                <div class="form-group">
                  <label for="address">地址</label>
                  <textarea id="address" v-model="accountForm.address" rows="4"></textarea>
                </div>
                
                <div class="form-actions">
                  <button type="submit" class="btn-save" :disabled="isSubmitting">
                    {{ isSubmitting ? '保存中...' : '保存修改' }}
                  </button>
                </div>
              </form>
            </div>
            
            <!-- 安全设置面板 -->
            <div v-else-if="activeTab === 'security'" class="security-panel">
              <div class="section-title">修改密码</div>
              <form @submit.prevent="updatePassword">
                <div class="form-group">
                  <label for="current-password">当前密码</label>
                  <input type="password" id="current-password" v-model="securityForm.currentPassword" required>
                </div>
                
                <div class="form-group">
                  <label for="new-password">新密码</label>
                  <input type="password" id="new-password" v-model="securityForm.newPassword" required minlength="8">
                  <small>密码至少8个字符，包含数字和字母</small>
                </div>
                
                <div class="form-group">
                  <label for="confirm-password">确认新密码</label>
                  <input type="password" id="confirm-password" v-model="securityForm.confirmPassword" required>
                </div>
                
                <div class="form-actions">
                  <button type="submit" class="btn-save" :disabled="isSubmitting || !passwordsMatch">
                    {{ isSubmitting ? '更新中...' : '更新密码' }}
                  </button>
                </div>
              </form>
              
              <div class="section-divider"></div>
              
              <div class="section-title">账号验证</div>
              <div class="verification-status">
                <div class="status-item">
                  <div class="status-label">手机验证</div>
                  <div class="status-value">{{ user.phoneVerified ? '已验证' : '未验证' }}</div>
                  <button class="btn-verify" v-if="!user.phoneVerified">立即验证</button>
                  <button class="btn-change" v-else>修改</button>
                </div>
                
                <div class="status-item">
                  <div class="status-label">邮箱验证</div>
                  <div class="status-value">{{ user.emailVerified ? '已验证' : '未验证' }}</div>
                  <button class="btn-verify" v-if="!user.emailVerified">立即验证</button>
                  <button class="btn-change" v-else>修改</button>
                </div>
              </div>
            </div>
            
            <!-- 消息通知面板 -->
            <div v-else-if="activeTab === 'notification'" class="notification-panel">
              <div class="section-title">通知设置</div>
              <div class="settings-list">
                <div class="setting-item">
                  <div class="setting-info">
                    <div class="setting-title">有人给我发消息</div>
                    <div class="setting-desc">当有买家或卖家给你发送消息时通知你</div>
                  </div>
                  <div class="setting-control">
                    <label class="toggle">
                      <input 
                        type="checkbox" 
                        v-model="notificationSettings.messages"
                        @change="updateSingleSetting('messages', notificationSettings.messages)"
                        :disabled="settingUpdating.messages"
                      >
                      <span class="slider"></span>
                    </label>
                  </div>
                </div>
                
                <div class="setting-item">
                  <div class="setting-info">
                    <div class="setting-title">有人收藏我的书籍</div>
                    <div class="setting-desc">当有人收藏你发布的书籍时通知你</div>
                  </div>
                  <div class="setting-control">
                    <label class="toggle">
                      <input 
                        type="checkbox" 
                        v-model="notificationSettings.favorites"
                        @change="updateSingleSetting('favorites', notificationSettings.favorites)"
                        :disabled="settingUpdating.favorites"
                      >
                      <span class="slider"></span>
                    </label>
                  </div>
                </div>
                
                <div class="setting-item">
                  <div class="setting-info">
                    <div class="setting-title">交易提醒</div>
                    <div class="setting-desc">当你的书籍有新的预订或完成交易时通知你</div>
                  </div>
                  <div class="setting-control">
                    <label class="toggle">
                      <input 
                        type="checkbox" 
                        v-model="notificationSettings.transactions"
                        @change="updateSingleSetting('transactions', notificationSettings.transactions)"
                        :disabled="settingUpdating.transactions"
                      >
                      <span class="slider"></span>
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 充值模态框 -->
      <Modal v-model="showRechargeModal" title="余额充值" width="450px">
        <div class="recharge-modal-content">
          <div class="recharge-options">
            <button 
              v-for="amount in rechargeOptions" 
              :key="amount" 
              class="recharge-option" 
              :class="{ active: rechargeAmount == amount }"
              @click="selectRechargeAmount(amount)"
            >
              ¥{{ amount }}
            </button>
          </div>
          
          <div class="custom-amount">
            <label for="custom-amount">自定义金额</label>
            <input 
              type="number" 
              id="custom-amount" 
              v-model="rechargeAmount" 
              placeholder="请输入充值金额" 
              min="0.01" 
              step="0.01"
            >
          </div>
          
          <div class="payment-methods">
            <h4>选择支付方式</h4>
            <div class="payment-options">
              <div 
                class="payment-option" 
                :class="{ active: paymentMethod === 'alipay' }" 
                @click="selectPaymentMethod('alipay')"
              >
                <img src="@/assets/alipay.png" alt="支付宝" class="payment-icon">
                <span>支付宝</span>
              </div>
              <div 
                class="payment-option" 
                :class="{ active: paymentMethod === 'wechat' }" 
                @click="selectPaymentMethod('wechat')"
              >
                <img src="@/assets/wxpay.png" alt="微信支付" class="payment-icon">
                <span>微信支付</span>
              </div>
            </div>
          </div>
        </div>
        
        <template #footer>
          <button class="btn-cancel" @click="showRechargeModal = false">取消</button>
          <button 
            class="btn-confirm" 
            @click="handleRecharge" 
            :disabled="isRecharging || !rechargeAmount || rechargeAmount <= 0 || !paymentMethod"
          >
            {{ isRecharging ? '充值中...' : '确认充值' }}
          </button>
        </template>
      </Modal>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import NavBar from '../components/NavBar.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import Modal from '../components/Modal.vue'
import { useRouter } from 'vue-router'
import api from '@/api/apiClient'
import fileUtil from '@/utils/fileUtil'
import { ElMessage } from 'element-plus'

const activeTab = ref('account')
const isSubmitting = ref(false)
const router = useRouter()
const isLoading = ref(true) // Track loading state
const avatarUrl = ref('') // 头像URL，初始化为空字符串而不是null
const previewAvatar = ref(null) // 头像预览URL
const error = ref(null) // 错误信息
const showRechargeModal = ref(false) // 控制充值模态框显示
const rechargeAmount = ref('') // 充值金额
const isRecharging = ref(false) // 充值状态
const paymentMethod = ref('') // 支付方式：'alipay' 或 'wechat'
const isAvatarLoading = ref(true) // 头像加载状态

// 预设充值金额选项
const rechargeOptions = [10, 20, 50, 100, 200, 500]

// 用户信息
const user = reactive({
  username: '加载中...',
  department: '加载中...',
  student_id: '加载中...',
  phoneVerified: false,
  emailVerified: false,
  publishedCount: 0,
  soldCount: 0,
  favoriteCount: 0,
  boughtCount: 0, // 新增已购买书籍数量字段
  bio: '',
  balance: 0, // 新增余额字段
  address: '' // 新增地址字段
})

// 账号表单
const accountForm = reactive({
  username: '',
  real_name: '',
  department: '',
  student_id: '',
  email: '',
  phone: '',
  wechat: '',
  bio: '',
  address: '' // 新增地址字段
})

// 安全表单
const securityForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 通知设置
const notificationSettings = reactive({
  messages: true,
  favorites: true,
  transactions: true,
})

// 新密码与确认密码是否匹配
const passwordsMatch = computed(() => {
  return securityForm.newPassword === securityForm.confirmPassword
})

//确认新密码是否符合格式要求
// 密码至少8个字符，包含数字和字母
const passwordWithSpecialCharsRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,}$/;
const isPasswordValid = computed(() => {
  return passwordWithSpecialCharsRegex.test(securityForm.newPassword)
})



// 获取用户头像
const fetchUserAvatar = async () => {
  try {
    console.log('开始获取用户头像...')
    
    // 使用工具类获取头像
    const result = await fileUtil.downloadAvatar()
    
    // 检查noAvatar标记
    if (result && result.noAvatar === true) {
      console.log('检测到用户未设置头像，使用默认头像')
      avatarUrl.value = '' // 使用默认头像
      return
    }
    
    if (result && result.success) {
      console.log('头像获取成功')
      avatarUrl.value = result.imageUrl
    } else {
      console.error('获取头像失败:', result?.message || '未知错误')
      avatarUrl.value = '' // 设置为空字符串，让模板使用默认头像
    }
  } catch (error) {
    console.error('获取头像过程中发生错误:', error)
    avatarUrl.value = '' // 设置为空字符串，让模板使用默认头像
  }
}

// 触发文件上传对话框
const triggerFileUpload = () => {
  document.getElementById('avatar-upload').click()
}

// 处理头像文件选择
const handleAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  try {
    // 使用工具类预览文件
    previewAvatar.value = await fileUtil.previewFile(file)
    
    // 显示上传中
    isSubmitting.value = true
    
    // 使用工具类上传头像
    const result = await fileUtil.uploadAvatar(file)
    
    if (result.success) {
      ElMessage.success(result.message)
      // 不刷新页面，设置头像已更新标志
      localStorage.setItem('avatarUpdated', 'true')
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('处理头像文件发生错误:', error)
    ElMessage.error(error.message || '处理头像文件失败')
  } finally {
    isSubmitting.value = false
  }
}

// 获取用户信息
const fetchUserProfile = async () => {
  isLoading.value = true
  error.value = null
  isAvatarLoading.value = true
  
  try {
    console.log('开始获取用户资料...')
    const response = await api.user.getProfile()
    console.log('获取用户资料成功:', response)
    
    // 检查响应是否有效
    if (!response || typeof response !== 'object') {
      error.value = '服务器未返回数据'
      isLoading.value = false // 确保在出错时结束加载状态
      isAvatarLoading.value = false
      return
    }

    // 从响应中提取用户数据
    let userData = null
    
    // 处理标准API响应格式 {code, message, data}
    if (response.code === 200 && response.data) {
      userData = response.data
      console.log('从标准响应中提取用户数据:', userData)
    } 
    // 后备处理：响应本身就是数据
    else {
      userData = response
      console.log('响应本身就是用户数据:', userData)
    }
    
    if (!userData || typeof userData !== 'object') {
      error.value = '获取用户信息失败: 数据格式错误'
      isLoading.value = false // 确保在出错时结束加载状态
      isAvatarLoading.value = false
      return
    }
    
    // 填充用户对象
    user.username = userData.username || ''
    user.department = userData.department || ''
    user.student_id = userData.student_id || ''
    user.phoneVerified = !!userData.phone
    user.emailVerified = !!userData.email
    user.publishedCount = userData.bookCount || 0
    user.soldCount = userData.soldCount || 0
    user.favoriteCount = userData.favoriteCount || 0
    user.boughtCount = userData.boughtCount || 0
    user.balance = userData.balance || 0 // 设置用户余额
    user.address = userData.address || '' // 设置用户地址
    
    // 填充账号表单
    accountForm.username = userData.username || ''
    accountForm.real_name = userData.real_name || ''
    accountForm.department = userData.department || ''
    accountForm.student_id = userData.student_id || ''
    accountForm.email = userData.email || ''
    accountForm.phone = userData.phone || ''
    accountForm.wechat = userData.wechat || ''
    accountForm.bio = userData.bio || ''
    accountForm.address = userData.address || '' // 填充地址表单
    
    console.log('用户信息填充完成，开始获取头像')
    
    // 获取用户设置信息（异步获取设置，不影响页面显示）
    fetchUserSettings()
    
    // 先检查用户是否有头像
    const avatarUpdated = localStorage.getItem('avatarUpdated') === 'true'
    
    if (userData.avatar === true || avatarUpdated) {
      // 如果设置了头像更新标志，清除它
      if (avatarUpdated) {
        localStorage.removeItem('avatarUpdated')
      }
      
      console.log('检测到用户有头像，等待头像加载完成')
      
      try {
        // 同步等待头像加载完成
        await fetchUserAvatar()
      } catch (e) {
        console.error('加载头像失败:', e)
        // 加载失败时使用默认头像，但不影响页面显示
        avatarUrl.value = ''
      }
    } else {
      console.log('用户没有设置头像，使用默认头像')
      avatarUrl.value = ''
    }
    
    console.log('头像加载完成，显示页面')
    isAvatarLoading.value = false
    isLoading.value = false // 头像加载完成后，结束页面加载状态
    
  } catch (e) {
    console.error('获取用户信息失败:', e)
    error.value = '获取用户信息失败，请重试'
    isLoading.value = false // 确保在出错时结束加载状态
    isAvatarLoading.value = false
  }
}

// 获取用户设置信息
const fetchUserSettings = async () => {
  try {
    console.log('开始获取用户设置...')
    const response = await api.user.getSettings()
    console.log('获取用户设置成功:', response)
    
    // 检查响应是否有效
    if (!response || typeof response !== 'object') {
      console.error('获取用户设置失败: 服务器未返回数据')
      return
    }
    
    // 从响应中提取设置数据
    let settingsData = null
    
    // 处理标准API响应格式 {code, message, data}
    if (response.code === 200 && response.data) {
      settingsData = response.data
      console.log('从标准响应中提取设置数据:', settingsData)
    } 
    // 后备处理：响应本身就是数据
    else {
      settingsData = response
      console.log('响应本身就是设置数据:', settingsData)
    }
    
    if (!settingsData || typeof settingsData !== 'object') {
      console.error('获取用户设置失败: 数据格式错误')
      return
    }
    
    // 更新通知设置
    notificationSettings.messages = Boolean(settingsData.notification_messages)
    notificationSettings.favorites = Boolean(settingsData.notification_favorites)
    notificationSettings.transactions = Boolean(settingsData.notification_transactions)
    
    console.log('用户设置更新完成:', notificationSettings)
  } catch (error) {
    console.error('获取用户设置失败:', error)
  }
}

const updateAccount = async () => {
  isSubmitting.value = true
  
  try {
    // 调用API更新用户资料，不包含username
    const response = await api.user.updateInfo({
      real_name: accountForm.real_name,
      department: accountForm.department,
      student_id: accountForm.student_id,
      email: accountForm.email,
      phone: accountForm.phone,
      wechat: accountForm.wechat,
      bio: accountForm.bio,
      address: accountForm.address // 添加地址字段更新
    })
    
    // 更新用户显示信息
    user.department = response.department
    user.student_id = response.student_id
    user.address = response.address // 更新地址信息
    
    ElMessage.success('账号信息更新成功！')
  } catch (error) {
    ElMessage.error(error.message || '更新失败，请重试')
    console.error('更新账号信息失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

const updatePassword = async () => {
  if (!passwordsMatch.value) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }
  if (!isPasswordValid.value) {
    ElMessage.warning('密码格式不正确，至少8个字符，包含数字和字母')
    return
  }
  
  isSubmitting.value = true
  
  try {
    // 调用API修改密码
    await api.user.modifyPassword({
      oldPassword: securityForm.currentPassword,
      newPassword: securityForm.newPassword
    })
    
    ElMessage.success('密码修改成功！')
    
    // 清空表单
    securityForm.currentPassword = ''
    securityForm.newPassword = ''
    securityForm.confirmPassword = ''
  } catch (error) {
    ElMessage.error(error.message || '密码修改失败，请检查旧密码是否正确')
    console.error('修改密码失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

const saveNotificationSettings = async () => {
  isSubmitting.value = true
  
  try {
    // 调用API保存通知设置
    await api.user.updateSettings({
      notification_messages: notificationSettings.messages,
      notification_favorites: notificationSettings.favorites,
      notification_transactions: notificationSettings.transactions,
    })
    
    ElMessage.success('通知设置保存成功！')
  } catch (error) {
    ElMessage.error(error.message || '保存失败，请重试')
    console.error('保存通知设置失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

const navigateToBooks = (type) => {
  router.push({
    path: '/my-books',
    query: { tab: type }
  })
}

// 页面加载时获取用户信息
onMounted(() => {
  // 确保用户已登录，检查登录状态
  checkLoginStatus()
  
  // 获取用户信息
  fetchUserProfile()
})

// 检查登录状态，如果未登录则重定向到登录页
const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  const loginStatus = localStorage.getItem('isLoggedIn') === 'true'
  
  console.log('检查登录状态:', loginStatus ? '已登录' : '未登录', 'token:', token ? '存在' : '不存在')
  
  // 如果未登录，重定向到登录页
  if (!loginStatus || !token) {
    console.log('用户未登录，重定向到登录页')
    router.push('/login')
    return false
  }
  
  // 确保isLoggedIn状态一致
  if (!loginStatus && token) {
    console.log('发现token存在但登录状态不一致，修正')
    localStorage.setItem('isLoggedIn', 'true')
  }
  
  return true
}

// 处理图片加载错误 - 增强版本
const handleImageError = (event) => {
  console.error('头像加载失败，使用默认头像');
  
  // 将src设置为默认头像
  try {
    // 使用public目录下的头像
    event.target.src = '/avatar.png';
    // 防止无限错误循环
    event.target.onerror = null;
  } catch (e) {
    console.error('加载默认头像失败:', e);
    // 如果默认头像也加载失败，使用内联样式显示占位符
    event.target.src = '';
    event.target.style.backgroundColor = '#cccccc';
  }
}

// 点击预设充值金额选项
const selectRechargeAmount = (amount) => {
  rechargeAmount.value = amount
}

// 选择支付方式
const selectPaymentMethod = (method) => {
  paymentMethod.value = method
}

// 重置充值表单
const resetRechargeForm = () => {
  rechargeAmount.value = ''
  paymentMethod.value = ''
}

// 处理充值
const handleRecharge = async () => {
  if (!rechargeAmount.value || rechargeAmount.value <= 0) {
    ElMessage.warning('请输入有效的充值金额（大于0）')
    return
  }
  
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }
  
  try {
    isRecharging.value = true
    
    // 调用充值API (注意这里不传递支付方式参数，按照需求只是UI展示用)
    await api.user.rechargeBalance(rechargeAmount.value)
    
    // 充值成功后更新余额
    const response = await api.user.getProfile()
    if (response && response.balance !== undefined) {
      user.balance = response.balance
    }
    
    ElMessage.success('充值成功！')
    showRechargeModal.value = false
    resetRechargeForm()
  } catch (error) {
    ElMessage.error(error.message || '充值失败，请重试')
    console.error('充值失败:', error)
  } finally {
    isRecharging.value = false
  }
}

// 新增的updateSingleSetting函数
const settingUpdating = reactive({
  messages: false,
  favorites: false,
  transactions: false,
})

const updateSingleSetting = async (setting, value) => {
  try {
    // 设置更新状态
    settingUpdating[setting] = true
    
    // 准备要更新的参数对象，包含所有设置的当前值
    const updateData = {
      notification_messages: notificationSettings.messages,
      notification_favorites: notificationSettings.favorites,
      notification_transactions: notificationSettings.transactions,
    }
    
    // 更新当前变更的设置值
    updateData[`notification_${setting}`] = value
    
    // 调用API保存所有设置
    await api.user.updateSettings(updateData)
    
    // 保存成功，显示提示
    ElMessage.success(`${getSettingText(setting)}设置已更新`)
  } catch (error) {
    // 出错时还原开关状态
    notificationSettings[setting] = !value
    ElMessage.error(error.message || '设置更新失败，请重试')
    console.error('更新设置失败:', error)
  } finally {
    // 无论成功或失败，都取消加载状态
    settingUpdating[setting] = false
  }
}

// 获取设置的中文名称
const getSettingText = (setting) => {
  const texts = {
    'messages': '消息通知',
    'favorites': '收藏通知',
    'transactions': '交易通知'
  }
  return texts[setting] || '通知'
}
</script>

<style scoped>
/* 容器样式 */
.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  font-size: 1.8rem;
  color: #1f2937;
  margin-bottom: 2rem;
}

.profile-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  margin-bottom: 2rem;
}

.profile-header {
  display: flex;
  align-items: center;
}

.avatar-container {
  position: relative;
  margin-right: 2rem;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 3px solid #fff;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.edit-avatar {
  background: none;
  border: none;
  color: white;
  font-size: 0.9rem;
  cursor: pointer;
  padding: 0.5rem;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.icon-camera::before {
  content: "📷";
  font-size: 1.2rem;
  margin-bottom: 5px;
}

.user-info {
  flex: 1;
}

.user-info h2 {
  margin: 0 0 0.5rem;
  font-size: 1.5rem;
  color: #1f2937;
}

.user-status {
  color: #6b7280;
  margin-bottom: 1rem;
}

.user-balance-container {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
}

.user-balance {
  color: #6b7280;
  margin-bottom: 0;
  margin-right: 1rem;
}

.balance-amount {
  color: #10b981; /* 绿色表示金钱 */
  font-weight: bold;
}

.user-stats {
  display: flex;
  gap: 2rem;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-item.clickable {
  cursor: pointer;
  transition: transform 0.2s;
  padding: 0.5rem 1rem;
  border-radius: 8px;
}

.stat-item.clickable:hover {
  background-color: #f3f4f6;
  transform: translateY(-2px);
}

.stat-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #1f2937;
}

.stat-label {
  color: #6b7280;
  font-size: 0.9rem;
}

.tab-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tab-buttons {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
}

.tab-btn {
  padding: 1rem 1.5rem;
  background: none;
  border: none;
  font-size: 1rem;
  font-weight: 500;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s;
}

.tab-btn:hover {
  color: #3b82f6;
}

.tab-btn.active {
  color: #3b82f6;
  box-shadow: inset 0 -2px 0 #3b82f6;
}

.tab-content {
  padding: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #374151;
}

.form-group small {
  display: block;
  margin-top: 0.25rem;
  color: #6b7280;
  font-size: 0.8rem;
}

input[type="text"],
input[type="password"],
input[type="email"],
input[type="tel"],
textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus,
textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-actions {
  margin-top: 2rem;
  display: flex;
  justify-content: flex-end;
}

.btn-save {
  padding: 0.75rem 1.5rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-save:hover:not(:disabled) {
  background-color: #2563eb;
}

.btn-save:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.section-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 1.5rem;
}

.section-divider {
  height: 1px;
  background-color: #e5e7eb;
  margin: 2.5rem 0;
}

.verification-status {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.status-item {
  display: flex;
  align-items: center;
}

.status-label {
  flex: 1;
  font-weight: 500;
  color: #374151;
}

.status-value {
  margin: 0 1.5rem;
  color: #6b7280;
}

.btn-verify, .btn-change {
  padding: 0.5rem 1rem;
  background-color: #f3f4f6;
  color: #4b5563;
  border: none;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
}

.btn-verify:hover, .btn-change:hover {
  background-color: #e5e7eb;
}

.settings-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.setting-item {
  display: flex;
  align-items: center;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.setting-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.setting-info {
  flex: 1;
}

.setting-title {
  font-weight: 500;
  color: #374151;
  margin-bottom: 0.25rem;
}

.setting-desc {
  color: #6b7280;
  font-size: 0.9rem;
}

.toggle {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.toggle input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #e5e7eb;
  transition: .4s;
  border-radius: 24px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #3b82f6;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    text-align: center;
  }
  
  .avatar-container {
    margin-right: 0;
    margin-bottom: 1.5rem;
  }
  
  .edit-avatar {
    opacity: 1;
  }
  
  .tab-buttons {
    overflow-x: auto;
    white-space: nowrap;
  }
}

.error-message-box {
  background-color: #fee2e2;
  border: 1px solid #ef4444;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  text-align: center;
}

.retry-button {
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.5rem 1rem;
  font-weight: 500;
  cursor: pointer;
  margin-top: 1rem;
}

.retry-button:hover {
  background-color: #dc2626;
}

.btn-recharge {
  background-color: #10b981;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.3rem 0.8rem;
  font-size: 0.9rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-recharge:hover {
  background-color: #059669;
}

/* 充值模态框样式 */
.recharge-modal-content {
  padding: 1rem 0;
}

.recharge-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.8rem;
  margin-bottom: 1.5rem;
}

.recharge-option {
  padding: 0.8rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background: white;
  text-align: center;
  font-size: 1.1rem;
  cursor: pointer;
  transition: all 0.2s;
}

.recharge-option:hover {
  border-color: #10b981;
  color: #10b981;
}

.recharge-option.active {
  background-color: #10b981;
  color: white;
  border-color: #10b981;
}

.custom-amount {
  margin-top: 1rem;
}

.custom-amount label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #374151;
}

.custom-amount input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 1rem;
}

.btn-cancel {
  padding: 0.6rem 1.2rem;
  background-color: #f3f4f6;
  color: #4b5563;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-cancel:hover {
  background-color: #e5e7eb;
}

.btn-confirm {
  padding: 0.6rem 1.2rem;
  background-color: #10b981;
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-confirm:hover:not(:disabled) {
  background-color: #059669;
}

.btn-confirm:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 支付方式样式 */
.payment-methods {
  margin-top: 1.5rem;
}

.payment-methods h4 {
  margin-bottom: 0.8rem;
  font-weight: 500;
  color: #374151;
}

.payment-options {
  display: flex;
  gap: 1rem;
}

.payment-option {
  flex: 1;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}

.payment-option:hover {
  border-color: #10b981;
}

.payment-option.active {
  border-color: #10b981;
  background-color: rgba(16, 185, 129, 0.1);
}

.payment-icon {
  height: 40px;
  margin-bottom: 0.5rem;
}
</style> 